let _Vue = null;

class VueRouter {
  // 构造函数
  constructor(options) {
    this.options = options;
    this.routeMap = {};
    this.data = _Vue.observable({
      current: "/"
    });
    this.createRouterMap();
    this.initComponent();
    this.initEvent();
  }

  // vue插件需要得静态方法
  static install(vue) {
    _Vue = vue;
    _Vue.mixin({
      beforeCreate() {
        console.log(this.$options);
        if (this.$options.router) {
          _Vue.prototype.$router = this.$options.router;
        }
      }
    });
  }

  // 生成路由表
  createRouterMap() {
    this.options.routes.forEach(item => {
      this.routeMap[item.path] = item.component;
    });
  }

  // 初始化路由组件(router-link router-view)
  initComponent() {
    _Vue.component("router-link", {
      props: { to: String },
      methods: {
        clickhander(e) {
          console.log(this);
          window.location.hash = '#' + this.to
          this.$router.data.current = this.to;
          e.preventDefault()
        }
      },
      render(h){
        console.log(this.$slots);
        return h("a", 
          { 
            attrs: { 
              href: this.to 
            }, 
            on: { 
              click: this.clickhander 
            } 
          }, [this.$slots.default]
        );
      }
    });
    _Vue.component("router-view", {
      render: h => {
        return h(this.routeMap[this.data.current]);
      }
    });
  }

  // 初始化浏览器事件（浏览器前进后退）
  initEvent() {
    window.addEventListener('hashchange',()=>{
      this.data.current = window.location.hash.slice(1)
    })
  }
}

export default VueRouter;
